/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.goods.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.JedisUtils;
import com.jeesite.modules.goods.entity.ZtMle;
import com.jeesite.modules.goods.entity.ZtSk;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.goods.entity.GoodsType;
import com.jeesite.modules.goods.entity.ZtGoods;
import com.jeesite.modules.goods.service.GoodsTypeService;
import com.jeesite.modules.goods.service.ZtGoodsService;
import com.jeesite.modules.sys.entity.UserDataScope;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.util.AliRequestUtils;

/**
 * 公司管理Controller
 * @author ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/goodsType")
public class GoodsTypeController extends BaseController {
	private String resultImg;
	private String imgName;
	@Autowired
	private GoodsTypeService goodsTypeService;
	@Autowired
	private ZtGoodsService ztGoodsService;
	@Autowired
	private MyProps myProps;
	
	/**
	 * 获取公司
	 */
	@ModelAttribute
	public GoodsType get(String goodsCode, boolean isNewRecord) {
		return goodsTypeService.get(goodsCode, isNewRecord);
	}

	/**
	 * 公司列表
	 * @param company
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "list")
	public String list(GoodsType goodsType, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/ztGoods/goodsTypeList";
	}

	/**
	 * 查询公司数据
	 * @param company
	 */
	
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<GoodsType> listData(GoodsType goodsType) {
		if (StringUtils.isBlank(goodsType.getParentCode())) {
			goodsType.setParentCode(GoodsType.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(goodsType.getViewCode())
				|| StringUtils.isNotBlank(goodsType.getName())
				){
			goodsType.setParentCode(null);
		}
		goodsTypeService.addDataScopeFilter(goodsType, UserDataScope.CTRL_PERMI_MANAGE);
		List<GoodsType> list = goodsTypeService.findList(goodsType);
		
		for(GoodsType gt:list){
			String type=gt.getType();
			if(StringUtils.isNotBlank(type)){
				String[] typeArr=type.split(",");
				String typeName="";
				for(String s:typeArr){
					 typeName+=DictUtils.getDictLabel("zt_goodsType_type", s, "0")+",";
				}
				typeName=typeName.substring(0,(typeName.length()-1));
				gt.setTypeName(typeName);
			}
		}
		return list;
	}
	/**
	 * 获取类型
	 * @param goodsType
	 * @return
	 */
	@RequestMapping(value = "getType")
	@ResponseBody
	public List<GoodsType> getType(String method,String viewCode) {
		List<GoodsType> list =new ArrayList<GoodsType>();
		if("initOne".equals(method)){
			GoodsType goodsType = new GoodsType();
			goodsType.setTreeLevel(0);
			
			goodsTypeService.addDataScopeFilter(goodsType, UserDataScope.CTRL_PERMI_MANAGE);
			list = goodsTypeService.findList(goodsType);
			
		}else if("getTwo".equals(method)){
			GoodsType goodsType = new GoodsType();
			goodsType.setTreeLevel(1);
			goodsType.setParentCode(viewCode);
			goodsTypeService.addDataScopeFilter(goodsType, UserDataScope.CTRL_PERMI_MANAGE);
			
			list = goodsTypeService.findList(goodsType);
		}else if("getThree".equals(method)){
			GoodsType goodsType = new GoodsType();
			goodsType.setTreeLevel(2);
			goodsType.setParentCode(viewCode);
			goodsTypeService.addDataScopeFilter(goodsType, UserDataScope.CTRL_PERMI_MANAGE);
			
			list = goodsTypeService.findList(goodsType);
		}
		
		return list;
	}
	
	
	/**
	 * 查看编辑
	 * @param 
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "form")
	public String form(GoodsType goodsType, Model model, HttpServletRequest request) {
		// 创建并初始化下一个节点信息
		goodsType = createNextNode(goodsType);
		
		model.addAttribute("goodsType", goodsType);
		
		return "modules/ztGoods/goodsTypeForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public GoodsType createNextNode(GoodsType goodsType) {
		if (StringUtils.isNotBlank(goodsType.getParentCode())) {
			goodsType.setParent(goodsTypeService.get(goodsType.getParentCode()));
		}
		if (goodsType.getIsNewRecord()) {
			GoodsType where = new GoodsType();
			where.setParentCode(goodsType.getParentCode());
			GoodsType last = goodsTypeService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				goodsType.setTreeSort(last.getTreeSort() + 30);
				goodsType.setViewCode(IdGen.nextCode(last.getViewCode()));
			}else if(goodsType.getParent() != null){
				goodsType.setViewCode(goodsType.getParent().getViewCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (goodsType.getTreeSort() == null){
			goodsType.setTreeSort(GoodsType.DEFAULT_TREE_SORT);
		}
		return goodsType;
	}
	
	/**
	 * 保存公司
	 * @param company
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated GoodsType goodsType) {
		if(StringUtils.isNotBlank(goodsType.getOldType())&&!goodsType.getType().equals(goodsType.getOldType())){
			
		goodsTypeService.setType(goodsType);
			
		}
		goodsTypeService.save(goodsType);
		
		imgName=goodsType.getImgname();
		resultImg=goodsType.getImg();
		if(StringUtils.isNotBlank(resultImg)&&!resultImg.startsWith("http")){
			resultImg=myProps.getServerPath()+resultImg;
		}
		
		 ExecutorService cachedThreadPool=Executors.newCachedThreadPool();
			cachedThreadPool.execute(new Runnable() {			
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try{
						AliRequestUtils.uploadFile(resultImg, imgName,"system365");
					}catch(Exception ex){}
				}
		});
		
		return renderResult(Global.TRUE, text("保存商品类型''{0}''成功", goodsType.getName()));
	}

	/**
	 * 停用类目
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(GoodsType goodsType) {
		goodsType.setState(2);
		goodsTypeService.setStatus(goodsType);
		
		goodsTypeService.updateStatus(goodsType);
		
	
		/*List<String> goodscodes=goodsTypeService.getGoodsCode(goodsType);
		
*/
		goodsType.setTreeLevel(goodsType.getTreeLevel()+1);
		ztGoodsService.updateSjStatusType(goodsType);
		
		return renderResult(Global.TRUE, text("停用类型及以下商品成功", goodsType.getName()));
	}
	
	/**
	 * 启用公司
	 * @param company
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(GoodsType goodsType) {
		
		goodsType.setState(1);
		goodsTypeService.setStatus(goodsType);
		
	/*	List<String> goodscodes=goodsTypeService.getGoodsCode(goodsType);
		
*/
		ztGoodsService.updateState(goodsType);
		
		return renderResult(Global.TRUE, text("启用类型及以下商品成功", goodsType.getName()));
	}

	/**
	 * 删除公司
	 * @param company
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(GoodsType goodsType) {
		goodsTypeService.delete(goodsType);
		return renderResult(Global.TRUE, text("删除类型''{0}''成功", goodsType.getName()));
	}
	
	

	/**
	 * 获取公司树结构数据
	 * @param excludeCode 排除的ID
	 * @param isAll 是否显示所有机构（true：不进行权限过滤）
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @param isShowFullName 是否显示全公司名称
	 * @return
	 */

	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, Boolean isAll, String isShowCode,
			String isShowFullName, String ctrlPermi) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		GoodsType where = new GoodsType();
		where.setState(1);
		if (!(isAll != null && isAll)){
			goodsTypeService.addDataScopeFilter(where, StringUtils.defaultIfBlank(
						ctrlPermi, UserDataScope.CTRL_PERMI_HAVE));
		}
		List<GoodsType> list = goodsTypeService.findList(where);
		for (int i = 0; i < list.size(); i++) {
			GoodsType e = list.get(i);
			// 过滤非正常的数据
			if (!GoodsType.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			String name = e.getName();
			
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getViewCode(), name));
			map.put("title", e.getName());
			mapList.add(map);
		}
		return mapList;
	}

	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData() {
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		goodsTypeService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	@RequestMapping(value = "setSk")
	public String setSk(Model model,String goodsCode,
						HttpServletRequest request, HttpServletResponse response) {
		ZtSk ztSk = new ZtSk();
		if(JedisUtils.getObject("ztSkContro"+goodsCode)!=null){
			ztSk=(ZtSk) JedisUtils.getObject("ztSkContro"+goodsCode);
		}
		ztSk.setGoodsCode(goodsCode);
		model.addAttribute("ztSk", ztSk);

		return "modules/ztTip/skGoodsCodeForm";
	}


	@PostMapping(value = "saveSk")
	@ResponseBody
	public String saveSk(ZtSk ztSk) {
		JedisUtils.setObject("ztSkContro"+ztSk.getGoodsCode(), ztSk, 0);

		return renderResult(Global.TRUE, text("保存成功！"));
	}



	@RequestMapping(value = "setMle")
	public String setMle(Model model,String goodsCode,
						 HttpServletRequest request, HttpServletResponse response) {
		ZtMle ztMle = new ZtMle();
		if(JedisUtils.getObject("ztMleContro"+goodsCode)!=null){
			ztMle=(ZtMle) JedisUtils.getObject("ztMleContro"+goodsCode);
		}
		ZtSk ztSk = new ZtSk();
		if(JedisUtils.getObject("ztSkContro"+goodsCode)!=null){
			ztSk=(ZtSk) JedisUtils.getObject("ztSkContro"+goodsCode);
		}
		ztSk.setGoodsCode(goodsCode);
		ztMle.setGoodsCode(goodsCode);
		model.addAttribute("ztSk", ztSk);

		model.addAttribute("ztMle", ztMle);

		return "modules/ztTip/mleGoodsCodeForm";
	}


	@PostMapping(value = "saveMle")
	@ResponseBody
	public String saveMle(ZtMle ztMle) {
		JedisUtils.setObject("ztMleContro"+ztMle.getGoodsCode(), ztMle, 0);

		return renderResult(Global.TRUE, text("保存成功！"));
	}
	/**
	 * 修改排序号
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "updateTreeSort")
	@ResponseBody
	public String updateTreeSort(String id ,Integer treeSort) {
		GoodsType goodsType = new GoodsType();
		goodsType.setId(id);
		goodsType=goodsTypeService.get(goodsType);
		goodsType.setTreeSort(treeSort);
		goodsTypeService.save(goodsType);
		return renderResult(Global.TRUE, "修改成功");
	}
	/**
	 * 删除类目折扣定价
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "deleteZtSk")
	@ResponseBody
	public String deleteZtSk(String goodsCode) {
		JedisUtils.delObject("ztSkContro"+goodsCode);
		return renderResult(Global.TRUE, "删除成功");
	}
	/**
	 * 删除类目毛利定价
	 */
	@RequiresPermissions("ztGoodsType:ztGoodsTypeData")
	@RequestMapping(value = "deleteZtMle")
	@ResponseBody
	public String deleteZtMle(String goodsCode) {
		JedisUtils.delObject("ztMleContro"+goodsCode);
		return renderResult(Global.TRUE, "删除成功");
	}
}